import React, { FC, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Header from '@/components/home/header'
import Address from '@/components/address/index'
import Loading from '@/components/home/loading/saleLoading'
import Course from '@/components/changeCourse/course'
import BtnGroup from '@/components/changeCourse/btnGroup'
import PopupSection from '@/components/changeCourse//popupSection'
import CourseDialog from '@/components/changeCourse/courseDialog'
import { customToast } from '@/components/customToast/index'
import EmptyChange from '@/components/changeCourse/empty'
import CourseNoticeBar from '@/components/changeCourse/courseNoticeBar'
import { getQueryVariable } from '@/utils/http'
import { useAppSelector, useAppDispatch } from '@/store'
import { initCurrendStdAdd, selectCurrendStdAdd } from '@/store/address'
import { getConfirmIndex, adjustAdd } from '@/api/changeCourse'
import { ConfirmData } from '@/types/changeCourse'
import iconChange from '@/assets/images/icon_change.png'

interface ConfirmParam {
  current: boolean
  changeData: ConfirmData
  clickVisible: (status: boolean) => void
}
const ConfirmItem: FC<ConfirmParam> = (props) => {
  const { changeData, current } = props
  return (
    <div
      className={
        'relative text-r1.3 leading-r1.6  text-gray-333333 mx-r0.4 px-r0.8 border-t border-white-F3F3F4 ' +
        (current ? 'py-r1.4' : 'pt-r1.4 pb-r1.5')
      }
      onClick={() => props.clickVisible(true)}
    >
      {current ? (
        <span>新赠课 X {changeData?.adjustInfo.targetGiftNames.length}</span>
      ) : (
        <span>原赠课 X {changeData?.adjustInfo.originGiftNames.length}</span>
      )}
      <div className="absolute leading-r1.6 h-r1.6 right-r0.8 top-r1.4">
        <i className="w-r1.6 h-r1.6 text-r1.6 iconfont icon-icon_arrow_right"></i>
      </div>
    </div>
  )
}
const changeCourseConfirm: FC<{}> = () => {
  const [loading, setLoading] = useState<boolean>(true)
  const [btnLoading, setBtnLoading] = useState<boolean>(false)
  const [visible, setVisible] = useState<boolean>(false)
  const [visiblePrice, setVisiblePrice] = useState<boolean>(false)
  const [dialogVisible, setDialogVisible] = useState<boolean>(false)
  const [changeData, setChangeData] = useState<ConfirmData>()
  const [reminder, setReminder] = useState<string[]>([
    '将使用一次调课机会',
    '将为您优先分配原班主任老师',
  ])
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const currendStdAdd = useAppSelector(selectCurrendStdAdd)
  const idEncode = getQueryVariable('idEncode') || ''
  const classValues =
    'rounded-bl-r1.6  px-r1.6 text-r2.2 leading-r4.0 text-center absolute right-0 top-0 text-white font-medium font-medium-family scale-50 origin-top-right '
  useEffect(() => {
    setLoading(true)
    getConfirmIndex({ idEncode: idEncode }).then((res) => {
      setLoading(false)
      if (res.result.status == 1) {
        setChangeData(res.result.data)
        if (res.result.data.adjustInfo.originGiftNames.length > 0) {
          setReminder((res: string[]) => {
            return res.concat([
              '原课程回放将收回，为您发放全部新课程内容',
              ' 原课程的赠课将换为新课程的赠课',
            ])
          })
        } else {
          setReminder((res: string[]) => {
            return res.concat(['将为您替换未学讲次，已学讲次可观看回放'])
          })
        }
        if (currendStdAdd && !currendStdAdd.id) {
          dispatch(initCurrendStdAdd(res.result.data.stuAdd))
        }
      }
    })
  }, [])
  const confirmBtn = async () => {
    setBtnLoading(true)
    //diffType 3 没有差价 1  补差价  2退回
    const params = changeData?.stuAdd?.id
      ? {
          idEncode: idEncode,
          orderType: changeData?.orderType,
          addId: currendStdAdd?.id ? currendStdAdd?.id : changeData?.stuAdd?.id,
        }
      : {
          idEncode: idEncode,
          orderType: changeData?.orderType,
        }
    adjustAdd(params).then((res) => {
      setBtnLoading(false)
      const newData = { ...res.result }
      function prop<T extends object, K extends keyof T>(obj: T, key: K) {
        return obj[key]
      }
      const result = prop(newData, 'data')
      if (newData.status === 1 && typeof result === 'object') {
        window.location.href = result.redirtUrl
      }
      if (res.result.status === 0 && typeof result === 'string') {
        customToast({ className: 'custom_toast_normal', text: result, duration: 2000 })
      }
    })
  }
  return (
    <div className="w-full h-full min-h-screen bg-gray-F7F7F8 overflow-auto font-normal font-regular">
      <Header
        cb={() => {
          navigate(-1)
        }}
        headerText={'调课确认'}
      ></Header>
      {loading ? <Loading noBorder={true} modal={true}></Loading> : null}
      {changeData ? (
        <>
          <CourseNoticeBar
            content={
              changeData.isSend == 1
                ? '课程变更讲义会重新邮寄，请您确认地址'
                : '存在班主任变更情况，成功后可前往"学习"中查看'
            }
          ></CourseNoticeBar>
          {changeData.isSend == 1 && <Address></Address>}
          <div className="text-gray-333333 px-r1.2 pb-r1.6 mt-r1.2">
            {changeData?.adjustInfo && (
              <div className="bg-white mb-r1.0 rounded-r0.8 relative pt-r1.2 shadow-bs5 overflow-hidden opacity-60">
                <div className="relative px-r1.2 py-r1.6">
                  <Course course={changeData?.adjustInfo.originProdInfos}></Course>
                </div>
                {changeData?.adjustInfo.originGiftNames.length > 0 && (
                  <ConfirmItem
                    changeData={changeData}
                    current={false}
                    clickVisible={() => setVisible(true)}
                  ></ConfirmItem>
                )}
                <div className={classValues + 'bg-gray-999999'}>原课程</div>
              </div>
            )}
            <div className="text-red-FF3627 text-r1.3 text-center leading-r1.4 my-r0.8 font-medium-family">
              <img
                alt=""
                src={iconChange}
                className="w-r1.4 h-r1.4 inline-block align-top mr-r0.4"
              />
              <span>调整</span>
            </div>
            {changeData?.adjustInfo && changeData?.productInfo && (
              <div className="bg-white mb-r1.0 rounded-r0.8 relative pt-r1.1 shadow-bs5 overflow-hidden border border-red-FF3627">
                <div className="relative px-r1.2 py-r1.6">
                  <Course course={changeData?.productInfo[0]} left={true}></Course>
                  <div className="absolute right-r1.2 bottom-r1.6 h-r1.6 z-10 text-red-FF3627 text-r1.2 leading-r1.6">
                    {changeData?.adjustInfo.priceInfo.diffType == 1 && '补差价'}
                    {changeData?.adjustInfo.priceInfo.diffType == 2 && '退回'}
                    <span className="ml-r0.2 mr-r0.2 font-SFProDisplay">¥</span>
                    <span className="font-semibold text-r1.6 leading-r1.6 font-SFProDisplay">
                      {changeData?.adjustInfo.priceInfo.diffPrice}
                    </span>
                  </div>
                </div>
                {changeData?.adjustInfo.targetGiftNames.length > 0 && (
                  <ConfirmItem
                    changeData={changeData}
                    current={true}
                    clickVisible={() => setVisible(true)}
                  ></ConfirmItem>
                )}
                <div className={classValues + ' bg-red-FF3627 shadow-bs6'}>新课程</div>
              </div>
            )}
          </div>
          <BtnGroup
            text={changeData?.adjustInfo?.priceInfo.diffType == 1 ? '去支付' : '确认调换'}
            showLeft={
              changeData?.adjustInfo?.priceInfo.diffType == 1 ||
              changeData?.adjustInfo?.priceInfo.diffType == 2
            }
            leftContent={
              <div className="w-r17.3">
                <div className="text-r1.2 text-gray-333333 leading-r1.5">
                  {changeData?.adjustInfo.priceInfo.diffType == 1 && '补差价：'}
                  {changeData?.adjustInfo.priceInfo.diffType == 2 && '退回：'}
                  <span className="-ml-r0.2 mr-r0.2 text-r1.3 text-red-FF3627 font-SFProDisplay">
                    ¥
                  </span>
                  <span className="font-SFProDisplay font-semibold text-r2.0 leading-r1.5 text-red-FF3627">
                    {changeData?.adjustInfo.priceInfo.diffPrice}
                  </span>
                </div>
                {changeData?.adjustInfo?.priceInfo.diffType == 1 && (
                  <div
                    className="relative bg-gray-F7F7F8 rounded-full h-r1.9 pl-r0.4 pr-r1.8 leading-r1.9 text-r1.1 text-gray-333333 inline-block mt-r0.4"
                    onClick={() => setVisiblePrice(true)}
                  >
                    查看明细
                    <div className="-rotate-90 w-r1.2 leading-r1.2 absolute right-r0.4 top-r0.5">
                      <i className="w-r1.2 h-r1.2 iconfont icon-icon_arrow_right"></i>
                    </div>
                  </div>
                )}
              </div>
            }
            disabled={btnLoading}
            loading={btnLoading}
            btnClick={() => setDialogVisible(true)}
          ></BtnGroup>
          <PopupSection
            visible={visible}
            title="赠课信息变化"
            content={
              <div className="-mt-r0.2 px-r0.4">
                <div className="text-gray-333333">
                  <div className="text-r1.5 leading-r2.0 font-medium-family mb-r0.8">新赠课：</div>
                  {changeData?.adjustInfo?.targetGiftNames.map((val, index) => (
                    <p key={index} className="mb-r0.5 text-r1.3 leading-r2.0">
                      {val}
                    </p>
                  ))}
                </div>
                <div className="text-gray-333333 mt-r2.2 opacity-60">
                  <div className="text-r1.5 leading-r2.0 font-medium-family mb-r0.8">
                    原赠课将收回：
                  </div>
                  {changeData?.adjustInfo?.originGiftNames.map((val, index) => (
                    <p key={index} className="mb-r0.5 text-r1.3 leading-r2.0">
                      {val}
                    </p>
                  ))}
                </div>
              </div>
            }
            changeVisible={(status: boolean) => setVisible(status)}
          ></PopupSection>
          <PopupSection
            visible={visiblePrice}
            title="价格明细"
            content={
              <div className="px-r0.4">
                <div className="flex justify-between text-r1.4 leading-r1.4 mb-r2.5">
                  <span>原课程实付款</span>
                  <span className="font-SFProDisplay font-semibold">
                    ¥{changeData?.adjustInfo?.priceInfo.originPrice}
                  </span>
                </div>
                <div className="flex justify-between text-r1.4 leading-r1.4 mb-r2.4">
                  <span>新课程金额</span>
                  <span className="font-SFProDisplay font-semibold">
                    ¥{changeData?.adjustInfo?.priceInfo.targetPrice}
                  </span>
                </div>
                <div className="border-t border-white-F3F3F4"></div>
                <div className="text-r1.2 text-gray-333333 leading-r1.5 text-right pt-r2.3">
                  补差价：
                  <span className="-ml-r0.2 mr-r0.2 text-r1.3 text-red-FF3627 font-SFProDisplay">
                    ¥
                  </span>
                  <span className="font-SFProDisplay font-semibold text-r2.0 leading-r1.5 text-red-FF3627">
                    {changeData?.adjustInfo?.priceInfo.diffPrice}
                  </span>
                </div>
              </div>
            }
            changeVisible={(status: boolean) => setVisiblePrice(status)}
          ></PopupSection>
          <CourseDialog
            visible={dialogVisible}
            title="是否确认调课"
            content={
              <ul className="m-0 text-left">
                {reminder.map((val, index) => (
                  <li key={index} className="mb-r0.8 pl-r0.8 relative">
                    <span className="w-r0.2 block h-r0.2 rounded-full bg-gray-333333 absolute left-0 top-r0.9"></span>
                    {val}
                  </li>
                ))}
              </ul>
            }
            confirmText="确定"
            onCancel={() => setDialogVisible(false)}
            onConfirm={() => confirmBtn()}
          ></CourseDialog>
        </>
      ) : (
        <EmptyChange content={['该课程无法调入，请返回重试']} />
      )}
    </div>
  )
}

export default changeCourseConfirm
